package com.nexgo.payment.trans.download;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.nexgo.common.ByteUtils;
import com.nexgo.data.entity.RecvData;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.trans.AbsOnlinePresenter;
import com.nexgo.payment.util.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 参数传递操作业务
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年07月13日
 */
public class TransParamPresenter extends AbsOnlinePresenter implements DownloadTransContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(TransParamPresenter.class.getSimpleName());

    private DownloadTransContract.View mView;

    public TransParamPresenter(@NonNull DownloadTransContract.View view, @NonNull DataSource repository) {
        super(view, repository);
        mView = checkNotNull(view);
        mView.setPresenter(this);
    }

    @Override
    protected TransData getTransData() {
        TransData transData = new TransData();
        transData.setTransType(TransType.PARAM_DOWN);
        return transData;
    }

    @Override
    protected void onFirstAction() {
        postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.param_down)));
    }

    @Override
    protected void onTransSuccess(RecvData recvData) {
        if (TextUtils.isEmpty(recvData.getField62())) {
            postMainThread(() -> mView.showTransFailed());
            return;
        }
        byte[] param = ByteUtils.hexString2ByteArray(recvData.getField62());
        byte field;
        byte[] fieldParam;
        String value;
        boolean isSuccess = true;
        for (int i = 0; i < param.length; ) {
            //取域
            field = ByteUtils.asciiByteArray2BcdArray(Arrays.copyOfRange(param, i, i + 2))[0];
            i += 2;
            mLog.debug("field {}", String.format(SysConstant.LOCALE, "%02x", field));
            switch (field) {
                case 0x11:                                                                            //POS终端应用类型
                    i += 2;
                    break;
                case 0x12:                                                                            //超时时间Bcd
                    fieldParam = Arrays.copyOfRange(param, i, i + 2);
                    int timeOut = Integer.parseInt(StringUtils.trimLeft(new String(fieldParam).trim(), '0'));
                    if (timeOut < 15) timeOut = 15;
                    mRepository.setParamValue(PreferencesConstants.COMMUNICATION_TIMEOUT, String.valueOf(timeOut));
                    i += 2;
                    break;
                case 0x13:                                                                //重试次数(重拨次数)
                    i += 1;
                    break;
                case 0x14:                                                                                //电话号码1
                case 0x15:                                                                                //电话号码2
                case 0x16:                                                                                //电话号码3
                case 0x17:                                                                                  //管理电话
                    i += 14;
                    break;
                case 0x18:                                                                                //是否支持小费
                    i += 1;
                    break;
                case 0x19:                                                                                                //小费百分比
                    i += 2;
                    break;
                case 0x20:                                                //是否支持手工输入卡号
                    fieldParam = Arrays.copyOfRange(param, i, i + 1);
                    value = new String(fieldParam);
                    if (TextUtils.isDigitsOnly(value)) {
                        mRepository.setParamValue(PreferencesConstants.ALLOW_MANUAL_PAN, value);
                    }
                    i += 1;
                    break;
                case 0x21:                                                                                                //是否自动签退
                    fieldParam = Arrays.copyOfRange(param, i, i + 1);
                    value = new String(fieldParam);
                    if (TextUtils.isDigitsOnly(value)) {
                        mRepository.setParamValue(PreferencesConstants.AUTO_LOGOUT_SWITCH, value);
                    }
                    i += 1;
                    break;
                case 0x22:                                                                                        //商户名称
                    fieldParam = Arrays.copyOfRange(param, i, i + 40);
                    try {
                        mRepository.setParamValue(PreferencesConstants.MERCHANT_NAME, new String(fieldParam, SysConstant.GBK).trim());
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    i += 40;
                    break;
                case 0x23:                                                                                                //交易重发次数
                    fieldParam = Arrays.copyOfRange(param, i, i + 1);
                    value = new String(fieldParam);
                    if (TextUtils.isDigitsOnly(value)) {
                        mRepository.setParamValue(PreferencesConstants.REVERSAL_UPLOAD_TIMES, value);
                    }
                    i += 1;
                    break;
                case 0x24:                                                                                                //离线交易上送方式 0:批结算之前一并上送 1:随下笔联机交易上?
                    i += 1;
                    break;
                case 0x25:                                                                                                //主密钥INDEX
                    fieldParam = Arrays.copyOfRange(param, i, i + 1);
                    value = new String(fieldParam);
                    if (TextUtils.isDigitsOnly(value)) {
                        mRepository.setParamValue(PreferencesConstants.MASTER_KEY_INDEX, value);
                    }
                    i += 1;
                    break;
                case 0x26:                                           //支持交易类型4字节(B32) 新文档规定16位之后取0
                    fieldParam = Arrays.copyOfRange(param, i, i + 4);
                    //fieldParam = ByteUtils.asciiByteArray2BcdArray(fieldParam);
                    int j = fieldParam[0];
                    int k;
                    boolean support;
                    for (k = 0; k < 8; k++) {
                        support = (j & 0x80) != 0x00;
                        j <<= 1;                                              //左移
                        switch (k) {
                            case 0:                                         //查询
                                mRepository.setParamValue(PreferencesConstants.QUERY_SWITCH, support ? "1" : "0");
                                break;
                            case 1:                                         //预授权/冲正
                                mRepository.setParamValue(PreferencesConstants.PRE_AUTH_SWITCH, support ? "1" : "0");
                                break;
                            case 2:                                         //预授权撤销/冲正
                                mRepository.setParamValue(PreferencesConstants.PRE_AUTH_VOID_SWITCH, support ? "1" : "0");
                                break;
                            case 3:                                         //预授权完成/冲正
                                mRepository.setParamValue(PreferencesConstants.PRE_AUTH_COMPLETE_SWITCH, support ? "1" : "0");
                                break;
                            case 4:                                         //预授权完成撤销/冲正
                                mRepository.setParamValue(PreferencesConstants.PRE_AUTH_COMPLETE_VOID_SWITCH, support ? "1" : "0");
                                break;
                            case 5:                                         //消费/冲正
                                mRepository.setParamValue(PreferencesConstants.SALE_SWITCH, support ? "1" : "0");
                                break;
                            case 6:                                         //消费撤销/冲正
                                mRepository.setParamValue(PreferencesConstants.SALE_VOID_SWITCH, support ? "1" : "0");
                                break;
                            case 7:                                         //退货
                                mRepository.setParamValue(PreferencesConstants.REFUND_SWITCH, support ? "1" : "0");
                                break;
                        }
                    }
                    j = fieldParam[1];                                              //第二个字节
                    for (k = 0; k < 8; k++) {
                        support = (j & 0x80) != 0x00;
                        j <<= 1;                                              //左移
                        switch (k) {
                            case 0:                                         //离线结算
                                break;
                            case 1:                                         //离线结算调整
                                break;
                            case 2:                                         //预授权完成离线
                                break;
                            case 3:                                         //IC卡脚本处理结果通知
                                break;
                            case 4:                                         //电子现金脱机消费
                                break;
                            case 5:
                                break;
                            case 6:                                         //电子钱包圈存类
                                break;
                            case 7:                                         //分期付款
                                break;
                        }
                    }
                    j = fieldParam[2];                                              //第三个字节
                    for (k = 0; k < 8; k++) {
                        support = (j & 0x80) != 0x00;
                        j <<= 1;                                              //左移
                        switch (k) {
                            case 0:                                         //分期付款消费撤销
                                break;
                            case 1:                                         //积分消费
                                break;
                            case 2:                                         //积分消费撤销
                                break;
                            case 3:                                         //圈存类 
                                break;
                            case 4:                                         //预约消费 
                                break;
                            case 5:                                         //预约消费撤销
                                break;
                            case 6:                                         //订购消费
                                break;
                            case 7:                                         //订购消费撤销
                                break;
                        }
                    }
                    j = fieldParam[3];                                              //第四个字节
                    for (k = 0; k < 8; k++) {
                        support = (j & 0x80) != 0x00;
                        j <<= 1;                                              //左移
                        switch (k) {
                            case 0:                                         //磁条卡现金(账户)充值 
                                break;
                            case 1:
                                break;
                            case 2:
                                break;
                            case 3:
                                break;
                            case 4:
                                break;
                            case 5:
                                break;
                            case 6:
                                break;
                            case 7:
                                break;
                        }
                    }
                    i += 4;
                    break;
                default:
                    i = param.length;
                    isSuccess = false;
                    break;
            }
            //不成功就直接退出循环
            if (!isSuccess) break;
        }
        if (isSuccess) {
            mRepository.syncParamValue();
            postMainThread(() -> mView.showTransSuccess());
        } else {
            postMainThread(() -> mView.showTransFailed());
        }
    }
}
